<template>
  <div class="App">
    <h1>MES资产盘点</h1>
    <div class="el-tree-select">
      <el-tree-select v-model="selectedLocation" :data="options" node-key="value"
        :props="{ label: 'label', children: 'children' }" :render-after-expand="false" style="width: 375px"
        placeholder="请选择位置" only-check-leaf :check-on-click-node="false" :expand-on-click-node="true" />
    </div>
    <div class="send">
      <textarea placeholder="填写编码后回车，或是用扫码枪扫描条码" v-model="input" @keydown.prevent.enter="scan" ref="inputField" />
      <button v-on:click="send">扫描后条码后点击批量上传位置记录</button>
    </div>
    <div v-if="message" class="alert">{{ message }}</div>
    <ul class="list">
      <li v-for="(v, i) in list" v-bind:key="i" class="list-item">
        <div class="content-container">
          <div class="time" style="font-size: 14px;">
            <span v-show="!v.Flag">采集的条码:</span>
            <span v-show="v.Flag">序列号：</span>{{ v.SerialNum }}
          </div>
          <div class="time" v-show="v.Flag">
            资产名称：{{ v.EquipmentName }}
          </div>
          <div class="time" style="color: red;">
            <span v-show="v.Flag">资产编码:</span>{{ v.AssetNum === "/" ? "暂无" : v.AssetNum }}
          </div>

          <el-button type="primary" class="button-container" size="small" @click="onAbnormal(i)">备注</el-button>
          <el-button type="danger" class="button-container1" size="small" @click="remove(i)">删除</el-button>

        </div>
        <div class="time" v-show="v.AbnormalInfo">
          <input v-model="v.AbnormalInfo" placeholder="请输入备注内容" :ref="(el) => setAbnormalInputRef(el, i)" class="abnormal-input" />
        </div>
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import localtions from "../assets/localtion.json";
import { client } from "../client";
import { ResGetOneData } from "../shared/protocols/PtlGetOneData";

const input = ref("");
const message = ref("");
const timeoutId: { value: number | null } = { value: null };
const options = ref(localtions || []);
const selectedLocation = ref("");
const list = ref([] as ResGetOneData["data"][]);
const abnormalInputs = ref<HTMLInputElement[]>([]);

const loadList = async () => {
  try {
    // 从 localStorage 中加载数据
    const savedList = localStorage.getItem("list");
    if (savedList) {
      const parsedList = JSON.parse(savedList);
      // 确保解析后的数据是一个数组
      if (Array.isArray(parsedList)) {
        list.value = parsedList;
      }
    }
  } catch (error) {
    console.error("Error loading list from localStorage:", error);
  }
};

// 删除该登记项
const remove = (index: number) => {
  list.value.splice(index, 1);
  localStorage.setItem("list", JSON.stringify(list.value));
};

const scan = async () => {
  if (!input.value.length) {
    message.value = "输入为空, 不能采集.";
    clearMessageAfterDelay();
    return;
  }

  // 检查输入是否已经存在于 list 中
  const isDuplicate = list.value.some((item) => item.SerialNum === input.value);
  const isDuplicate2 = list.value.some((item) => item.AssetNum === input.value);

  if (isDuplicate || isDuplicate2) {
    input.value = ""; // 清空输入框
    message.value = "输入的序列号或资产号已存在."; // 设置提示信息
    clearMessageAfterDelay();
    return;
  }

  let ret = await client.callApi("GetOneData", {
    ScanNum: input.value,
  });

  // Success
  if (ret.isSucc) {
    list.value.unshift(ret.res.data);
  } else {
    message.value = "条码不存在或未采集."; // 设置提示信息
    clearMessageAfterDelay();
    return;
  }

  localStorage.setItem("list", JSON.stringify(list.value));
  input.value = ""; // 清空输入框
};

const send = async () => {
  if (!list.value.length) {
    message.value = "你还没扫条码呢！";
    clearMessageAfterDelay();
    return;
  }

  // 验证地址是否完整
  if (!selectedLocation.value) {
    message.value = "请选择完整的位置信息！";
    clearMessageAfterDelay();
    return;
  }

  const Username = localStorage.getItem("username");

  // 获取选中节点的完整路径
  const getNodePath = (value, data) => {
    let path = '';

    const findNode = (value, data, parentPath = '') => {
      for (const node of data) {
        const currentPath = parentPath ? `${parentPath}/${node.label}` : node.label;

        if (node.value === value) {
          path = currentPath;
          return true;
        }

        if (node.children && node.children.length) {
          if (findNode(value, node.children, currentPath)) {
            return true;
          }
        }
      }
      return false;
    };

    findNode(value, data);
    return path;
  };

  // 生成上传要求的 Location
  const nodePath = getNodePath(selectedLocation.value, options.value);
  const Location = `一期${nodePath || selectedLocation.value}`;

  const req = list.value
    .filter((item) => item.Flag === true)
    .map((item) => {
      const { Flag, ...rest } = item;
      return rest;
    });

  try {
    await Promise.all(
      req.map((item) =>
        client.callApi("pandian/AddData", {
          AssetNum: item.AssetNum,
          EquipmentName: item.EquipmentName,
          EquipmentModel: item.EquipmentModel,
          SerialNum: item.SerialNum,
          AbnormalInfo: item.AbnormalInfo,
          User: "汤宇翔",
          Location: Location
        })
      )
    );

    list.value = [];
    localStorage.setItem("list", JSON.stringify(list.value));
    message.value = `${req.length}条数据上传成功！`;
  } catch (err) {
    message.value = "数据上传失败，请重试！";
  }
  clearMessageAfterDelay();
};

const clearMessageAfterDelay = () => {
  // 清除已有计时器
  if (timeoutId.value !== null) {
    clearTimeout(timeoutId.value);
  }
  // 创建新计时器并记录ID
  timeoutId.value = setTimeout(() => {
    message.value = "";
    timeoutId.value = null;
  }, 5000);
};

const onAbnormal = (i: number) => {
  list.value[i].AbnormalInfo = "备注：";
  nextTick(() => {
    if (abnormalInputs.value[i]) {
      abnormalInputs.value[i].focus();
    }
  });
};

const setAbnormalInputRef = (el: HTMLInputElement, index: number) => {
  if (el) {
    abnormalInputs.value[index] = el;
  }
};

onMounted(() => {
  loadList();
});

onBeforeUnmount(() => {
  if (timeoutId.value) {
    clearTimeout(timeoutId.value);
  }
});
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.App {
  text-align: center;
}

.App>* {
  margin: 20px auto;
}

.alert {
  color: red;
  font-weight: bold;
}

/* 树形选择器样式 */
:deep(.el-tree-select .el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-tree-select .el-tree) {
  min-width: 375px !important;
  width: 375px !important;
}

.send,
.list {
  width: 370px;
}

.send>* {
  display: block;
  width: 100%;
  margin: 10px auto;
  padding: 10px;
  border-radius: 5px;
  font-size: 16px;
  border: none;
  outline: none;
}

.send>textarea {
  height: 50px;
  background: #f7f7f7;
  border: #eeeeee 1px solid;
}

.send>textarea:focus {
  background: #fff;
  border-color: #ccc;
}

.send>button {
  background: #215fa4;
  color: white;
  cursor: pointer;
}

.send>button:hover {
  background: #4b80bb;
}

.list {
  list-style: none;
  border-radius: 5px;
  padding: 10px;
  background: #f2f2f2;
}

.list>li {
  position: relative;
  margin-bottom: 10px;
  padding: 10px;
  background: #fff;
  line-height: 1.5em;
  border-radius: 5px;
}

.button-container {
  position: absolute;
  top: 10px;
  right: 15px;
}

.button-container1 {
  position: absolute;
  top: 55px;
  right: 15px;
}

ul.list>li.list-item>div.content-container>div.time {
  text-align: left;
}

.abnormal-input {
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  font-size: 14px;
  border: 1px solid #ccc;
  outline: none;
}

.abnormal-input:focus {
  border-color: #4b80bb; /* 聚焦时的边框颜色 */
  box-shadow: 0 0 5px rgba(75, 128, 187, 0.5); /* 聚焦时的阴影效果 */
}
</style>
